package com.woniuxy.security.realm;

import com.woniuxy.security.service.UserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import javax.annotation.Resource;
import java.util.Map;

public class DbRealm extends AuthorizingRealm {
    @Resource
    private UserService userService;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        return null;
    }

    //登录验证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        //得到登录传来的token
        UsernamePasswordToken jwtToken = (UsernamePasswordToken) token ;
        //从token中得到用户名
        String account = jwtToken.getUsername();
        //验证用户信息，向用户服务请求
        Map<String,String> map = userService.accountAndPassword(account);
        if(map == null){
            //用户名错误
            throw new UnknownAccountException("账号："+account+"不存在！或者未激活！");
        }
        return new SimpleAuthenticationInfo(map.get("account"),map.get("password"),this.getName());
    }

    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof UsernamePasswordToken;
    }
}
